import React from 'react'
import { getGoodsDetails } from 'api/good'
import { addCollection, delCollection } from 'api/user'
import './shop.scss';
import { Carousel, message } from 'antd'
import {
  Link
} from 'react-router-dom';
import InputNumber from 'components/widget/inputNumber/inputNumber.jsx';
import Drawer from 'material-ui/Drawer';
import { addToCart } from 'api/cart';
export default class ShopDetail extends React.Component{
	constructor (props) {
		super(props)
		this.state = {
			details: {
				image_row: [],
        spec_name: []
			},
			current: 1,
      open: false,
      checkList: [],
      shopNumber: 1
		}
	}
	goBack () { //返回上一级
    this.props.history.goBack()
  }
	componentWillMount () {
		getGoodsDetails({
			cid: this.props.location.state.id
		}).then(res => {
			if (res.code === 1) {
				this.setState({
					details: res.data
				})
				if (res.data.good_spec_info.length > 0) {
					let checkList = []
					res.data.good_spec_info.forEach(() => {
						checkList.push(0)
					})
					this.setState({
						checkList: checkList
					})
				}
			}
		})
	}
	stopClick (e) {
		e.stopPropagation()
	}
	addShopToCart (e) {
		e.stopPropagation()
		let params = {
			shop_id: this.state.details.shop_id,
			cart_data: [{
				goods_id: this.state.details.sku_code_list.length !== 0 ? this.state.details.sku_code_list[this.calculateSkuid()] : this.state.details.common_id,
				goods_num: this.state.shopNumber
			}]
		}
		addToCart(params).then(res => {
			if (res.code === -403) {
				this.props.history.push({
          pathname: '/login'
        })
			}
			if (res.code === 1) {
				console.log(this.state.nowType)
				if (this.state.nowType === 1) {
					this.props.history.push({
						pathname: '/user/order/conOrder',
						state: {
							cart_ids: [
								res.data.cart_id
							]
						}
					})
				} else {
      		message.success('加入购物车成功！', 2, () => {
      			this.setState({
      				open: false
      			})
      		})
				}
			} else {
				message.error(res.message, 2, () => {
					this.setState({
						open: false
					})
				})
			}
		})
	}
	calculateSkuid () {
		let sku_id = 'sku'
		this.state.checkList.forEach((item, index) => {
			sku_id += !index ? this.state.details.good_spec_info[index][item].id : '_' + this.state.details.good_spec_info[index][item].id
		})
		return sku_id
	}
	priceCalcu () {
		let price = this.state.checkList.length > 0 ? this.state.details.goods_base_list[this.state.details.sku_code_list[this.calculateSkuid()]].goods_price : this.state.details.common_price
		return price*this.state.shopNumber
	}
	changeCheckList (e, index, i) { // 修改选中sku
		e.stopPropagation()
		let checkList = this.state.checkList
		checkList[index] = i
		this.setState({
			checkList: checkList,
			shopNumber: 1
		})
	}
	changeIndex (current) { // 图片滚动
		this.setState({
			current: current + 1
		})
	}
	// 购物sku添加
  toOpen (nowType) {
  	if (+this.state.details.common_price === 0) {
			message.warning('如想购买此商品, 请联系商家')
		} else {
			this.setState({
	      open: true,
	      nowType: nowType
	    })
		}
  }
  toClose () {
    this.setState({
      open: false
    })
  }
  colletShop = () => {
  	if (this.state.details.collect_flag) {
  		delCollection({
  			collect_type: 1,
  			collect_id: this.state.details.collect_id
  		}).then(res => {
  			if (res.code === -403) {
					this.props.history.push({
	          pathname: '/login'
	        })
				}
  			if (res.code === 1) {
  				message.success('取消收藏成功！', 2)
  				this.setState({
		  			details: {
		  				...this.state.details,
		  				collect_flag: !this.state.details.collect_flag
		  			}
		  		})
  			} else {
  				message.error(res.message, 2)
  			}
  		})
  	} else {
  		addCollection({
	  		collect_type: 1,
	  		common_id: this.state.details.common_id
	  	}).then(res => {
	  		if (res.code === -403) {
					this.props.history.push({
	          pathname: '/login'
	        })
				}
	  		if (res.code === 1) {
	  			message.success('收藏成功！', 2)
		  		this.setState({
		  			details: {
		  				...this.state.details,
		  				collect_flag: !this.state.details.collect_flag,
		  				collect_id: res.data.collect_id
		  			}
		  		})
	  		} else {
  				message.error(res.message, 2)
	  		}
	  	})
  	}
  }
  collectShops = () => {
  	if (this.state.details.shop_collect_flag) {
  		delCollection({
  			collect_type: 2,
  			collect_id: this.state.details.shop_collect_id

  		}).then(res => {
  			if (res.code === -403) {
					this.props.history.push({
	          pathname: '/login'
	        })
				}
  			if (res.code === 1) {
  				message.success('取消收藏成功！', 2)
  				this.setState({
		  			details: {
		  				...this.state.details,
		  				shop_collect_flag: !this.state.details.shop_collect_flag
		  			}
		  		})
  			} else {
  				message.error(res.message, 2)
  			}
  		})
  	} else {
  		addCollection({
	  		collect_type: 2,
	  		shop_name: this.state.details.shop_name,
	  		shop_id: this.state.details.shop_id
	  	}).then(res => {
	  		if (res.code === -403) {
					this.props.history.push({
	          pathname: '/login'
	        })
				}
	  		if (res.code === 1) {
	  			message.success('收藏成功！', 2)
		  		this.setState({
		  			details: {
		  				...this.state.details,
		  				shop_collect_flag: !this.state.details.shop_collect_flag,
		  				shop_collect_id: res.data
		  			}
		  		})
	  		} else {
  				message.error(res.message, 2)
	  		}
	  	})
  	}
  }
  changeNumber (value) {
  	this.setState({
  		shopNumber: value
  	})
  }
	render() {
		return (
			<div style={{backgroundColor: '#F1F1F1'}} className='shopGroup'>
				{<i className='glyphicon glyphicon-back fanhui' onClick={this.goBack.bind(this)}></i>}
				<div className='banner_group'>
					<Carousel dots={false} autoplay={true} afterChange={this.changeIndex.bind(this)}>
						{this.state.details.image_row.map((item, index) => {
							return (
								<img src={item} key={index}></img>
							)
						})}
					</Carousel>
					<div className='my_dots'>{`${this.state.current}/${this.state.details.image_row.length}`}</div>
				</div>
				<div className="desc_group">
					{this.state.details.common_name}
				</div>
				{
					+this.state.details.common_price === 0 ?
					<div className="shop_price">
						面议
					</div>
					:
					<div className="shop_price">
						￥{this.state.details.common_price}
					</div>
				}
				<div className='shop_limit'>
					<div className="flex">
						<div>运费：￥{this.state.details.common_freight}</div>
						<div>销量：{this.state.details.common_salenum}</div>
					</div>
				</div>
				<div className="shop_market">
					<Link to={{
							pathname: '/company',
            state: {shop_id: this.state.details.shop_id}
          }} className="market__desc">
						<img src={this.state.details.shop_logo} />
						<div className="flex">
							<div>{this.state.details.shop_name}</div>
							<div>
								<div className="inline-block">
									<div className='font-big' style={{color: '#333'}}>{this.state.details.goods_count}</div>
									<div>全部商品</div>
								</div>
								<div className="inline-block">
									<div className='font-big' style={{color: '#333'}}>{this.state.details.collect_count}</div>
									<div>收藏人数</div>
								</div>
							</div>
						</div>
					</Link>
					<div className="market__btn">
						<div className={this.state.details.shop_collect_flag ? 'text-center active' : 'text-center'} onClick={this.collectShops}>
							<i className='glyphicon-collect glyphicon'></i> 收藏店铺
						</div>
						<div className='text-center'>
							<Link to={{pathname: '/company/companyclassify', state: {
								shop_id: this.state.details.shop_id
							}}}>
								<i className='glyphicon-classify1 glyphicon'></i> 商品分类
							</Link>
						</div>
					</div>
				</div>
				<div className="shop_group" style={{marginTop: '.667rem'}}>
					<div className="shop__title">
						商品详情
					</div>
					<div className="shop__content" style={{marginTop: '.667rem'}} dangerouslySetInnerHTML={{__html: this.state.details.detail}}>
					</div>
				</div>
				<div className="footer_group">
					<Link to={{
							pathname: '/company',
            state: {shop_id: this.state.details.shop_id}
          }} className='inline-block'>
						<i className='glyphicon-shopping glyphicon'></i>
						<div>店铺</div>
					</Link>
					<div className={this.state.details.collect_flag ? 'inline-block active' : 'inline-block'} onClick={this.colletShop} >
						<i className='glyphicon-collect glyphicon'></i>
						<div>收藏</div>
					</div>
					<Link to={{pathname: '/Cart'}} className='inline-block'>
						<i className='glyphicon-cart glyphicon'></i>
						<div>进货单</div>
					</Link>
					<div className="foot__btn" style={+this.state.details.common_price === 0 ? {backgroundColor: '#ccc', color: '#999'} : {backgroundColor: '#FFD0D0', color: '#DF1212'}} onClick={this.toOpen.bind(this, 2)}>
						加入进货单
					</div>
					<div  className="foot__btn" style={+this.state.details.common_price === 0 ? {backgroundColor: '#999', color: '#ccc'} : {backgroundColor: '#DF1212', color: 'white'}} onClick={this.toOpen.bind(this, 1)}>
						立即购买
					</div>
				</div>
        <Drawer anchor="bottom" open={this.state.open} onClose={this.toClose.bind(this)}>
          <div
            tabIndex={0}
            role="button"
            onClick={this.toClose.bind(this)}
          >
            <div className="buy_group">
              <div className="flex" style={{marginBottom: '.666667rem'}}>
                <img src={this.state.details.common_image} />
                <div className="buy_group__price">
                  商城价: <span>￥{this.state.checkList.length > 0 ? this.state.details.goods_base_list[this.state.details.sku_code_list[this.calculateSkuid()]].goods_price : this.state.details.common_price}</span>
                </div>
              </div>
              {this.state.details.common_spec_name ? <div>
                {this.state.details.common_spec_name.length !== 0 && this.state.details.good_spec_info.length !== 0 ? this.state.details.common_spec_name.map((item, index) => {
                  return (
                    <div className='sku_group' key={index}>
                      <div className='sku_title'>
                        {item}：
                      </div>
                      <div className='sku_content flex'>
                        {this.state.details.good_spec_info[index].map((item, i) => {
                          return (
                            <div className={this.state.checkList[index] === i ? 'sku_rect active' : 'sku_rect'} key={item.id} onClick={(e) => this.changeCheckList(e, index, i)}>
                              {item.name}
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )
                }) : ''}
              </div> : ''}
              <div className='flex sku_limit' onClick={this.stopClick}>
                <div>数量选择：</div>
                <div className='flex'>
                  <div>库存：{this.state.checkList.length > 0 ? this.state.details.goods_base_list[this.state.details.sku_code_list[this.calculateSkuid()]].goods_stock : '999'}</div>
                  <InputNumber shopNumber={this.state.shopNumber} changeNum={value => this.changeNumber(value)} max={this.state.checkList.length > 0 ? +this.state.details.goods_base_list[this.state.details.sku_code_list[this.calculateSkuid()]].goods_stock : this.state.details.common_stock}/>
                </div>
              </div>
            </div>
            <div className='total__of'>
              共<span>{this.state.shopNumber}</span>件<span>￥{this.priceCalcu().toFixed(2)}</span>
          </div>
          <div className="buy_btn" onClick={(e) => this.addShopToCart(e)}>
            确定
          </div>
          </div>
        </Drawer>
			</div>
		)
	}
}
